package com.kayeah82.application.avatar.qq.initializer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePropertySource;

import java.io.File;
import java.io.IOException;
import java.util.Properties;

/**
 * 环境变量初始化
 *
 * @author kayeah82
 * */
public class HomeInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {

	private static final Logger logger = LoggerFactory.getLogger(HomeInitializer.class);

	private String[] artifactIds;
	private String module;

	public HomeInitializer(String module, String... artifactIds) {
		this.module = module;
		this.artifactIds = artifactIds;
	}

	public HomeInitializer(String module) {
		this.module = module;
	}

	@Override
	public void initialize(ConfigurableApplicationContext applicationContext) {
		HomeStructure structure;

		try {
			if (artifactIds == null || artifactIds.length == 0) {
				structure = HomeStructure.env();
			} else {
				structure = HomeStructure.env(artifactIds);
			}
		} catch (Exception e) {
			logger.error("bad or missing home env/property");
			throw e;
		}

		Properties properties = System.getProperties();
		structure.dumpStructure(properties);

		logger.info("home set to: " + structure.getHomeDirectory());

		MutablePropertySources propertySources = applicationContext.getEnvironment().getPropertySources();
		File confDirectory = structure.getConfDirectory();

		logger.debug("trying overrides");
		this.addConfigFile(new File(confDirectory, "overrides.properties"), propertySources);

		if (this.module != null) {
			String moduleConfigName = String.format("overrides-%s.properties", this.module);

			logger.debug("trying module overrides");
			this.addConfigFile(new File(confDirectory, moduleConfigName), propertySources);

			properties.put("spring.pid.file", structure.getTempDirectory() + File.separator + module + ".pid");
		}

	}

	private void addConfigFile(File configFile, MutablePropertySources propertySources) {
		String configFilePath = configFile.getPath();
		Resource configResource = new FileSystemResource(configFile);

		if (!configResource.exists()) {
			logger.error("missing config file: " + configFilePath);
			return;
		}

		ResourcePropertySource propertySource;

		try {
			propertySource = new ResourcePropertySource(configResource);
		} catch (IOException e) {
			logger.warn("failed adding config file", e);
			return;
		}

		propertySources.addFirst(propertySource);

		logger.info("added config file: " + configFilePath);
	}
}
